package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"net/http/cookiejar"
	"os"
)

// 手动设置cookie
func rrCookie() {
	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}
	firstRequest, _ := http.NewRequest("GET", "http://httpbin.org/cookies/set?name=wjf", nil)
	firstResponse, _ := client.Do(firstRequest)
	defer firstResponse.Body.Close()

	secondRequest, _ := http.NewRequest("GET", "http://httpbin.org/cookies", nil)
	for _, cookie := range firstResponse.Cookies() {
		secondRequest.AddCookie(cookie)
	}
	secondResponse, _ := client.Do(secondRequest)
	defer secondResponse.Body.Close()

	content, _ := ioutil.ReadAll(secondResponse.Body)
	fmt.Printf("1 %s\n", content)

	r, _ := http.Get("http://httpbin.org/cookies/set?name=wjf")
	defer r.Body.Close()
	content, _ = ioutil.ReadAll(r.Body)
	fmt.Printf("2 %s\n", content)
}

// cookie 持久化,通过jar的自动持久化cookie
func jarCookie() {
	jar, _ := cookiejar.New(nil)
	client := &http.Client{
		Jar: jar,
	}

	r, _ := client.Get("http://httpbin.org/cookies/set?name=wjf")
	defer r.Body.Close()
	_, _ = io.Copy(os.Stdout, r.Body)
}

func main() {
	jarCookie()
}
